package com.pzl.simple.wvlib;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


/**
 * 专门用来html、h5浏览交互的webiew activity
 * 启用单进程模式创建，不影响主进程业务，单进程内存给webview加速（系统加载页面默认加载在内存）
 * 业务主进程通过AIDL与webview进程通信交互
 */
public class WebVeiwBrowserActivity extends AppCompatActivity {

    public static final String CONTENT_SCHEME = "file:///android_asset/";
    private final String netUrl = "https://hao.360.com/";
    private final String nativeAssets = "TEST1.html";
    private String url = CONTENT_SCHEME + nativeAssets;

    private static WebVeiwBrowserActivity instance;
    private WebView webView;
    MainHandler handler = new MainHandler();

    //主进程通讯接口
    private static IMainService mainProxy;
    ServiceConnection connectionMainService = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("jinx", "onServiceConnected = " + name +
                    "\n进程 = " + Utils.getCurProcessName(WebVeiwBrowserActivity.this) + "\n"
                    + "线程 = " + Thread.currentThread().getName());
            mainProxy = IMainService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("jinx", "onServiceDisconnected = " + name);
        }
    };


    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        //启动主进程所在的service
        bindService(new Intent(this, MainServiceImpl.class), connectionMainService, BIND_AUTO_CREATE);

        setContentView(R.layout.activity_web_veiw_browser);
        webView = findViewById(R.id.wv);
        try {
            getSupportActionBar().hide();
        } catch (Exception e) {
        }

        Utils.webSettings(webView);
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new JsInterfaceTool(this, handler), "android");
        webView.loadUrl(url);


    }


    public static WebVeiwBrowserActivity getInstance() {
        return instance;
    }

    /**
     * 调用js
     *
     * @param jsFunction
     * @param beanJsonStr
     */
    public void callJS(final String jsFunction, final String beanJsonStr) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                //webview相关所有方法的调用必须在同一个线程里
                Utils.callJS(webView, jsFunction, beanJsonStr);
            }
        });
    }


    static class MainHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what != 1001) return;
            Bundle bundle = msg.getData();
            String cmd = bundle.getString("cmd");
            String param = bundle.getString("param");
            try {
                mainProxy.handleJsCall(cmd, param);//把调用传递给主进程的调用
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("jinx", e.getMessage());
            }
        }

    }


}
